package com.tyx.chargingpile.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tyx.chargingpile.Enum.ServiceExceptionEume;
import com.tyx.chargingpile.Enum.ServiceMessageEume;
import com.tyx.chargingpile.service.ChargingPileService;
import com.tyx.chargingpile.service.HttpAPIService;
import com.tyx.chargingpile.service.MessageService;
import com.tyx.chargingpile.service.exception.ServiceExcep;
import com.tyx.chargingpile.util.Util;
import com.tyx.chargingpile.vo.HttpResult;
import com.tyx.chargingpile.vo.SocketResponseResult;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 刷卡信息上报请求鉴权
 */
@Service("chargingPileCardMsgReportCheck")
public class ChargingPileCardMsgReportCheck implements ChargingPileService {

    @Value("${chargingback.url}")
    private String url;
    @Autowired
    HttpAPIService httpAPIService;

    private final static Logger LOGGER = LoggerFactory.getLogger(ChargingPileCardMsgReportCheck.class);

    @Override
    public SocketResponseResult execute(ChannelHandlerContext channelHandlerContext, byte[] context) throws Exception {
        String commandId = MessageService.getCommandControl(context);
        String channelId = channelHandlerContext.channel().id().toString();
        Map<String,String> map = MessageService.analysisMessage(context, ServiceMessageEume.REPORTCHECK.getUpLinePath());
        checkData(map);
        String pileNum = map.get("pileNum");
        pileNum = pileNum.substring(1,pileNum.length());
        String gunpointNum = map.get("gunpointNum");
        // 对枪口编号，进行转换，如果前面有0的，转换掉
        gunpointNum = Integer.parseInt(map.get("gunpointNum")) + "";
        String cardNo = map.get("cardNo");
        String physicalCardNo = map.get("physicalCardNo");
        String balacnce = map.get("balacnce");
        // 转化为元的单位
        balacnce = Double.parseDouble(balacnce)/100  + "";
        sendMsg(pileNum,gunpointNum,cardNo,physicalCardNo,balacnce,channelId,commandId);

        Map<String ,String> dwn = new HashMap<>();
        dwn.put("gunpointNum",gunpointNum);
        dwn.put("powerType",map.get("powerType"));
        dwn.put("pileNum",map.get("pileNum"));
        dwn.put("cardNo",map.get("cardNo"));
        dwn.put("physicalCardNo",map.get("physicalCardNo"));
        dwn.put("commandBack","FF");
        byte[] dwnContext = MessageService.getMessage(dwn,ServiceMessageEume.REPORTCHECK.getDwnLinePath());
        ByteBuf pingMessage = Unpooled.buffer();
        pingMessage.writeBytes(dwnContext);
        channelHandlerContext.writeAndFlush(pingMessage);
//        LOGGER.info("刷卡信息上报请求鉴权下行报文:" + Util.BCD2String(dwnContext));
        LOGGER.info("客户端"+channelId+",指令控制编号："+commandId+",桩编号:" + pileNum + ",刷卡信息上报请求鉴权下行报文" + Util.BCD2String(dwnContext));
        return new SocketResponseResult(channelHandlerContext,dwnContext);
    }

    @Override
    public SocketResponseResult execute(ChannelHandlerContext channelHandlerContext, Map data) throws Exception {
        return null;
    }

    @Async
    public void sendMsg(String pileNum, String gunpointNum, String cardNo, String physicalCardNo, String balacnce,String channelId,String commandId){
        try {
            JSONObject requestJson = new JSONObject();
            JSONObject dataJson = new JSONObject();
            dataJson.put("DeviceId",pileNum);
            dataJson.put("ChargePortIndex",gunpointNum);
            dataJson.put("PhysicalId",physicalCardNo);
            dataJson.put("CardId",cardNo);
            dataJson.put("AmountMoney",balacnce);
            requestJson.put("MainCMD",68);
            requestJson.put("SubCMD",11);
            requestJson.put("Data",dataJson);
            LOGGER.info("客户端"+channelId+",指令控制编号："+commandId+",桩编号:" + pileNum + ",刷卡信息上报请求鉴权推送至后台" + requestJson.toJSONString());
            HttpResult result = httpAPIService.doPost2Json(url,requestJson.toJSONString());
            if(result.getCode() != 200){
                LOGGER.info("客户端"+channelId+",指令控制编号："+commandId+",桩编号:" + pileNum + ",刷卡信息上报请求鉴权推送至后台：false");
            }
            LOGGER.info("客户端"+channelId+",指令控制编号："+commandId+",桩编号:" + pileNum + ",刷卡信息上报请求鉴权推送至后台：true");
        }catch (Exception e){
            e.printStackTrace();
            LOGGER.info("客户端"+channelId+",指令控制编号："+commandId+",桩编号:" + pileNum + ",刷卡信息上报请求鉴权推送至后台: 报错"+ e.getMessage());
        }
    }

    /**
     * 报文业务校验
     * @param map
     * @throws ServiceExcep
     */
    private void checkData(Map<String,String> map) throws ServiceExcep {
        if(map == null){
            throw new ServiceExcep(ServiceExceptionEume.MESSAGEPARSINGERROR);
        }
        String pileNum = map.get("pileNum");
        String gunpointNum = map.get("gunpointNum");
        // 对枪口编号，进行转换，如果前面有0的，转换掉
        String cardNo = map.get("cardNo");
        String physicalCardNo = map.get("physicalCardNo");
        String balacnce = map.get("balacnce");
        if (TextUtils.isEmpty(pileNum) || TextUtils.isEmpty(gunpointNum) ||TextUtils.isEmpty(cardNo) ||TextUtils.isEmpty(physicalCardNo) ||TextUtils.isEmpty(balacnce) ){
            throw new ServiceExcep(ServiceExceptionEume.INCOMPLETEPARAMETERS);
        }
    }
}
